import axios from "axios";
import router from "@/router";
import Cookie from "js-cookie";
import Qs from "qs";
import store from "@/store";
//进度条
import NProgress from "nprogress";
import "nprogress/nprogress.css";

//进度条
NProgress.configure({
  easing: "ease", // 动画方式
  speed: 500, // 递增进度条的速度
  showSpinner: false, // 是否显示加载ico
  trickleSpeed: 200, // 自动递增间隔
  minimum: 0.3, // 初始化时的最小百分比
});

let baseURL = "";
let action = "";
if (process.env.NODE_ENV === "development") {
  //是否为开发判断
  baseURL = "/m.api"; //上线前
  action = "/upload/admin";
} else {
  baseURL = "http://zxwyit.cn:8080/m.api"; //上线后
  action = "http://zxwyit.cn:8080/upload/admin";
}
// 创建axios实例
const instance = axios.create({
  // baseURL,
  headers: { "content-type": "application/x-www-form-urlencoded" },
});

// 添加请求拦截器
let token = Cookie.get("token");
instance.interceptors.request.use(
  (config) => {
    // 在发送请求之前做些什么----给请求添加请求头token
    config.headers["AdminToken"] = Cookie.get("token");
    NProgress.start(); //进度开始
    return config;
  },
  function (error) {
    // 对请求错误做些什么
    console.log(error);
    return Promise.reject(error);
  }
);
const requestType = ["_mt=delete", "_mt=create", "_mt=edit"];
// 添加响应拦截器
instance.interceptors.response.use(
  async function (res) {
    let data = res.data;
    const { errno, errmsg } = data;
    let path = router.currentRoute.value.fullPath; // 获取当前路由
    //判断token是否已过期
    if (10006 == errno) {
      // 获取当前接口请求数据
      const configData = res.config.data || "";
      // 判断类型是否需要无痛刷新index!=-1需要无痛刷新(includes判断是否含有)
      var index = requestType.findIndex((item) => configData.includes(item));
      if (-1 === index) {
        //不需要无痛
        ElMessage.error(errmsg);
        // 跳转到登录
        router.replace({ path: "/login", query: { back: path } });
      } else {
        //需要无痛
        const { password, username } = store.state.userinfo.userInfo;
        //1重新获取token
        let loginData = { _mt: "login", _gp: "admin", username, password };
        const { errno, errmsg, data } = await post(loginData);
        if (200 == errno) {
          Cookie.set("token", data);
        } else {
          ElMessage.error(errmsg);
          router.replace({ path: "/login", query: { back: path } });
          return Promise.reject({ errno, errmsg, data });
        }
        return instance.request(res.config);
      }
    } else if (200 != errno) {
      // 其他错误状态码
      NProgress.done();
      ElMessage.error(errmsg);
      return;
    }
    NProgress.done();
    return data;
  },
  function (error) {
    // 对响应错误做点什么
    router.replace({ path: "/login" });
    console.log(error);
    return Promise.reject(error);
  }
);
function upload(data) {
  return instance.post(action, data);
}
function post(data, params) {
  return instance.post(baseURL, Qs.stringify(data), { params });
}
// get接口
function get(params) {
  return instance.get(baseURL, { params });
}

export { get, post, upload, action, token };
